<?php

defined('SYSPATH') or die('Access error!');

class Model_User extends Model
{

    public $rules = array(
        'mobile_phone' => array
            (
            'phone' => array(11),
        ),
        'qq' => array(
            'digit' => array(TRUE),
            'max_length' => array(12)
        )
    );

    /**
     *  根据用户的id号 得到对应的资料
     * @param type $id
     * @return type
     */
    public function get_user_by_id($id, $params = '')
    {
        $data = $this->get_row(array('id' => $id), $params);
        if (count($data) > 0)
        {
            return $data;
        }
        return array();
    }

    /**
     * 插入用户资料
     * @param array $data
     * @return type 
     */
    public function insert_user($data)
    {
        $data['add_ip'] = URL::get_ip();
        $data['last_ip'] = URL::get_ip();
        $data['add_time'] = Date::get_time();
        $data['last_time'] = Date::get_time();
        $data['login_num'] = 1;
        //获取默认的用户组id
        $group_id = Model::factory('user_group')->get_var(array('is_default' => 1), 'id');
        $data['group_id'] = $group_id;
        $data['active'] = USER_UNACTIVE;
        $data['password'] = $this->create_password($data['password'], $data['safecode']);
        $user_id = $this->insert($data);
        //生成用户账户资料
        Model_User_Account::factory('user_account')->create_user_account($user_id);
        return $user_id;
    }

    /**
     *  存入用户信息到session
     * @param type $data
     */
    public function login($data)
    {
        $detail = array();
        $user_detail = $this->get_user_info_by_username($data['username']);
        $detail['login_num'] = $user_detail['login_num'] + 1;
        $detail['last_ip'] = URL::get_ip();
        $detail['last_time'] = time();
        $user_detail['avatar_path'] = $this->create_avatar_path($user_detail['id'], $user_detail['avatar']);
        $user_detail = Arr::merge($user_detail, Model::factory('user_account')->get_user_account($user_detail['id'], 'points,experience,amount'));
        Session::instance()->set('user', $user_detail);
        $this->update($detail, array('id' => $user_detail['id']));
        return $user_detail['id'];
    }

    public function cookie_login($data)
    {

        if (empty($data['username']))
        {
            /* 摧毁cookie */
            $time = Date::get_time() - 3600;
            Cookie::set("JSW_USER[user_id]", '', $time);
            Cookie::set("JSW_USER[password]", '', $time);
        }
        else
        {
            /* 设置cookie */
            $time = Date::get_time() +60*60*24*7;
            Cookie::set("JSW_USER[username]", $data['username'], $time);
            Cookie::set("JSW_USER[user_id]", $data['user_id'], $time);
            Cookie::set("JSW_USER[password]", $data['password'], $time);
        }
    }

    public function create_avatar_path($user_id, $avatar)
    {
        if (!empty($avatar))
        {
            return USER_AVATAR_PATH . '/' . $user_id . '/small_' . $avatar;
        }

        return USER_AVATAR_PATH . '/tavatar.gif';
    }

    /**
     *  检查用户资料
     * @param type $username
     * @param type $password
     * @return boolean|string
     */
    public function check_user($username, $password)
    {
        //根据用户的username获取用户资料
        $user_detail = $this->get_user_info_by_username($username);
        if (count($user_detail) > 0)
        {
            if ($this->create_password($password, $user_detail['safecode']) != $user_detail['password'])
            {
                return FALSE;
            }
            return TRUE;
        }

        return FALSE;
    }

    /**
     *  根据用户名查找用户基本资料
     * @param type $username
     * @return type
     */
    public function get_user_info_by_username($username)
    {
        $user_detail = $this->get_row(array('username' => $username), 'id,username,email,safecode,password,login_num,active,is_admin,avatar,theme');
        return count($user_detail) > 0 ? $user_detail : array();
    }

    /**
     *  根据用户的id获取用户的详细信息
     * @param type $id
     * @return type
     */
    public function get_user_info_by_id($id)
    {
        $sql = "SELECT u.*,ug.name as group_name,uc.points,uc.amount,uc.experience  FROM " . $this->db->get_table('user') . " AS u" .
                " LEFT JOIN  " . $this->db->get_table('user_group') . " AS ug" .
                " ON u.group_id=ug.id" .
                " LEFT JOIN " . $this->db->get_table('user_account') . " AS uc" .
                " ON uc.user_id=u.id" .
                " WHERE u.id=" . intval($id);
        $user_detail = $this->db->get_row($sql, ARRAY_A);
        $user_detail['birthday'] = Date::timeformat($user_detail['birthday'], 2);
        $user_detail['avatar_path'] = $this->create_avatar_path(Session::instance()->get_detail('user', 'id'), $user_detail['avatar']);
        return count($user_detail) > 0 ? $user_detail : array();
    }

    public function get_company_info_by_id($id)
    {
        $company_detail = $this->get_row(array('id' => $id), 'company_name,company_attr,company_work_attr,company_job,company_works,company_address,company_code,company_phone,company_description');

        if ($company_detail['company_works'] != '')
        {
            $company_detail['company_works'] = explode(',', $company_detail['company_works']);
        }
        return count($company_detail) > 0 ? $company_detail : array();
    }

    /**
     *  查看用户是否已经登录
     * @return type
     */
    public function logged_in()
    {
        return count(Session::instance()->get('user')) > 0;
    }

    /**
     *  生成用户密码
     * @param type $password
     * @param type $safecode
     * @return type 
     */
    public function create_password($password, $safecode)
    {
        return md5(md5($password) . $safecode);
    }

    public function change_user_password($data)
    {

        $password = $this->create_password($data['password'], $data['safecode']);

        return $this->update(array('password' => $password), array('id' => $data['id']));
    }

    /**
     *  获取用户列表
     * @param type $where_sql
     * @param type $nums
     * @return type
     */
    public function get_user_list($where_sql = '', $nums = 10)
    {
        $where = ' ';
        if (Arr::validate_arr($where_sql))
        {
            $where .= $this->get_table_where('u', $where_sql);
        }
        $where .= ' ORDER BY u.id DESC';
        $sql = 'SELECT u.username,u.is_admin,u.status,u.email,u.id,u.last_time,ug.name as group_name ' .
                "FROM " . $this->table . " AS u " .
                "LEFT JOIN " . $this->db->get_table('user_group') . " AS ug ON ug.id = u.group_id " . $where;
        $data = $this->get_page_list($sql, $nums);
        return $data;
    }

    /**
     *  根据条件获取用户的数量
     * @param type $where
     * @return type
     */
    public function get_count_user($where = '')
    {
        $sql = "SELECT COUNT(*) FROM " . $this->table . " as u WHERE " . $where;
        return $this->db->get_var($sql);
    }

    /**
     * 获得模版的信息
     *
     * @access  private
     * @param   string      $template_name      模版名
     * @return  array
     */
    public function get_themes_info($template_name)
    {
        $info = array();
        $info['code'] = $template_name;
        $info['screenshot'] = '';
        if (file_exists(USER_TEMPLATE_STYLE . $template_name . "/screen.png"))
        {
            $info['screen'] = USER_TEMPLATE_SCREEN . '/' . $template_name . "/screen.png";
        }
        return $info;
    }

    /**
     *  根据用户的id获取相关权限
     * @param type $user_id
     * @return type
     */
    public function get_user_privilege($user_id = 0)
    {
        $user_id = intval($user_id);
        $group_id = 0;
        if ($user_id != 0)
        {
            $group_id = $this->get_var(array('id' => $user_id), 'group_id');
        }
        $sql = "SELECT gp.privilege_id,up.name " .
                "FROM " . $this->table . " AS u " .
                " LEFT JOIN " . $this->db->get_table('user_group_privilege') . " AS gp ON gp.group_id = u.group_id " .
                " LEFT JOIN " . $this->db->get_table('user_privilege') . " AS up ON up.id=gp.privilege_id " .
                " WHERE gp.group_id=" . $group_id . " AND u.id=" . $user_id;

        $privilege_list = $this->db->get_results($sql, ARRAY_A);
        return Arr::validate_arr($privilege_list) > 0 ? $privilege_list : array();
    }

    public function set_user_privilege()
    {
        //用户组英文名
        $group_en_name = $this->get_group_en_name();
        ACL::instance()->add_role($group_en_name);
        //获取用户的权限
        $user_privilege = Model_User_Group::factory('user_group')->get_group_privilege(array('en_name' => $group_en_name));
        if (Arr::validate_arr($user_privilege))
        {
            foreach ($user_privilege as $key => $value)
            {
                ACL::instance()->allow($group_en_name, $value['module'], $value['name']);
            }
        }
    }

    /**
     *   判断是否有权限操作某个操作
     * @param Request $request  当前请求
     * @param type $data        是否要提供多余数据
     * @return boolean
     */
    public function is_allowed(Request $request, $data = '')
    {
        //用户组英文名
        $group_en_name = $this->get_group_en_name();
        //根据module、controller、action、data获取对应的key
        $where_arr = array();
        if ($data != '')
        {
            $where_arr['data'] = $data;
        }
        $where_arr['controller'] = $request->controller;
        $where_arr['action'] = $request->action;
        $privilege_temp = Model_User_Privilege::factory('user_privilege')->get_row($where_arr, 'name,module');


        if (!ACL::instance()->is_allowed($group_en_name, $privilege_temp['module'], $privilege_temp['name']))
        {
            return FALSE;
        }
        return TRUE;
    }

    /**
     *  根据用户的id获取用户组的en_name
     * @return type
     */
    public function get_group_en_name()
    {
        //获取当前用户的权限
        if (Arr::validate_arr(Session::instance()->get('user')))
        {
            $user_id = Session::instance()->get_detail('user', 'id');
            //获取用户组的英文名
            $sql = "SELECT ug.en_name " .
                    "FROM " . $this->table . " AS u " .
                    "LEFT JOIN " . $this->db->get_table('user_group') . " AS ug ON ug.id=u.group_id " .
                    "WHERE u.id=" . $user_id;
            $group_en_name = $this->db->get_var($sql);
        }
        return !empty($group_en_name) ? $group_en_name : 'youke_user';
    }

}